﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Web.Mvc;
using Wikey.Domain.Components;


namespace Wikey.Web.Mvc {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : NinjectHttpApplication
    {

        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "DefaultList",
                "Pages",
                new {controller = "Page", action = "Index"}
                );

            routes.MapRoute(
                "ViewSpace",
                "Spaces/{spaceName}",
                new { controller = "Space", action = "Look", spaceName = string.Empty }
                );

            routes.MapRoute(
                "ViewPage",
                "Pages/{pageName}",
                new { controller = "Page", action = "Look", pageName = string.Empty }
                );

            routes.MapRoute(
                        "DataSourceJson",
                        "Data/{source}/{type}",
                        new { controller = "Data", action = "Get", source = string.Empty , type = "json" }
                        );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );


            
        }
       
   protected override void OnApplicationStarted()
        {

            Error += OnError;
            EndRequest += OnEndRequest;
            RegisterAllControllersIn("Wikey.Web.MVC");
            RegisterRoutes(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure();
        }

        private void OnEndRequest(object sender, EventArgs e)
        {
            if (((HttpApplication)sender).Context.Handler is MvcHandler)
            {
                CreateKernel().Get<ISessionSource>().Close();
            }
        }

        private void OnError(object sender, EventArgs e)
        {
            CreateKernel().Get<ISessionSource>().Close();
        }

        protected override void OnApplicationStopped()
        {
        }
        protected override IKernel CreateKernel()
        {
            return Factory.Kernel;
        }
    }
}